import { UniversalHttpClient } from "./http-client";
import { HttpRequestConfig } from "./types";

// URL参数替换函数
export function dealApiParams(apiUrl: string, params: Record<string, any> = {}): string {
  const reg = /{.*?}/g;
  const matchResult = apiUrl.match(reg);
  
  if (matchResult) {
    matchResult.forEach(match => {
      const replaceReg = /[{}]/g;
      const variable = match.replace(replaceReg, "");
      apiUrl = apiUrl.replace(match, params[variable] || '');
    });
  }
  
  return apiUrl;
}

// API工具类
export class ApiUtils {
  private httpClient: UniversalHttpClient;

  constructor(httpClient: UniversalHttpClient) {
    this.httpClient = httpClient;
  }

  // GET请求
  public get<T = any>(
    url: string,
    data?: Record<string, any>,
    config?: HttpRequestConfig
  ): Promise<T> {
    const processedUrl = dealApiParams(url, data);
    return this.httpClient.get<T>(processedUrl, { params: data }, config);
  }

  // POST请求
  public post<T = any>(
    url: string,
    data?: Record<string, any>,
    config?: HttpRequestConfig
  ): Promise<T> {
    const processedUrl = dealApiParams(url, data);
    return this.httpClient.post<T>(processedUrl, { data }, config);
  }

  // PUT请求
  public put<T = any>(
    url: string,
    data?: Record<string, any>,
    config?: HttpRequestConfig
  ): Promise<T> {
    const processedUrl = dealApiParams(url, data);
    return this.httpClient.put<T>(processedUrl, { data }, config);
  }

  // DELETE请求
  public delete<T = any>(
    url: string,
    data?: Record<string, any>,
    config?: HttpRequestConfig
  ): Promise<T> {
    const processedUrl = dealApiParams(url, data);
    return this.httpClient.delete<T>(processedUrl, { data }, config);
  }

  // PATCH请求
  public patch<T = any>(
    url: string,
    data?: Record<string, any>,
    config?: HttpRequestConfig
  ): Promise<T> {
    const processedUrl = dealApiParams(url, data);
    return this.httpClient.patch<T>(processedUrl, { data }, config);
  }
}